package cn.wolfcode.mq.listener;

import cn.wolfcode.core.WebsocketServer;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;

@RocketMQMessageListener(
        consumerGroup = MQConstant.ORDER_RESULT_CONSUMER_GROUP,
        topic = MQConstant.ORDER_RESULT_TOPIC
)
@Component
@Slf4j
public class OrderResultMessageListener implements RocketMQListener<OrderMQResult> {

    @Override
    public void onMessage(OrderMQResult result) {
        String json = JSON.toJSONString(result);
        log.info("[订单结果] 收到创建订单结果消息: {}", json);

        try {
            int count = 0;
            do {
                // 根据 token 获取到 session 对象
                Session session = WebsocketServer.SESSION_MAP.get(result.getToken());
                if (session != null) {
                    // 通过 session 对象, 将数据写到前端
                    session.getBasicRemote().sendText(json);
                    return;
                }

                count++;
                log.info("[订单结果] 第{}次查询 session 对象获取失败, 准备下一次获取...", count);
                // 睡一会儿再拿
                Thread.sleep(300);
            } while (count <= 5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
